<template>
  <div class="editor">
    <Button v-if="initing&&!isBatch" type="primary" class="back-button" @click="back()" icon="md-arrow-back">返回上一级</Button>

    <Card v-if="initing">
      <Row>
        <Form ref="model" :model="model" :rules="ruleInline" inline :label-width="110">
          <Col span="14">
          <Row>
            <Col span="12">
            <FormItem prop="eventsName" label="赛事名称">
              <Input v-model="model.eventsName" v-show="isEdit" style="width:200px;" placeholder="请输入" />
              <span v-show="!isEdit" v-text="modelTemp.eventsName"></span>
            </FormItem>
            </Col>
            <Col span="12" v-if="!isBatch">
            <FormItem prop="kindCode" label="赛事类型">
              <dict-span code="ZGX_SSDJ" :value="model.kindCode"></dict-span>
            </FormItem>
            </Col>
            <Col span="12" v-if="isBatch">
            <FormItem prop="kindCodes" label="赛事类型">
              <dict style="width:280px;" :multiple="isBatch" code="ZGX_SSDJ" model="model.kindCodes" :value="model.kindCodes" @click="getVal"></dict>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem prop="eventsEnglishName" label="赛事英文名">
              <Input v-model="model.eventsEnglishName" v-show="isEdit" style="width:200px;" placeholder="请输入" />
              <span v-show="!isEdit" v-text="modelTemp.eventsEnglishName"></span>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem prop="niandu" label="赛事年度">
              <DatePicker v-model="model.niandu" v-show="isEdit" type="year" placeholder="请选择" clearable style="width: 200px"></DatePicker>
              <span v-show="!isEdit" v-text="modelTemp.niandu"></span>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12" v-if="kindCode != 20">
              <FormItem prop="gradeCode" label="赛事级别">
                <dict code="ZGX_BSJB" model="model.gradeCode" :parentCode='kindCode' :value="model.gradeCode" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
                <dict-span v-show="!isEdit" :parentCode='kindCode' code="ZGX_BSJB" :value="modelTemp.gradeCode"></dict-span>
              </FormItem>
            <!-- <FormItem prop="competitionState" label="赛事状态">
              <dict code="ZGX_SSZTSX" model="model.competitionState" :value="model.competitionState" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
              <dict-span v-show="!isEdit" code="ZGX_SSZTSX" :value="modelTemp.competitionState"></dict-span>
            </FormItem> -->
            </Col>
            <Col span="12">
              <FormItem prop="planField" label="计划场次">
                <Input v-model="model.planField" v-show="isEdit" style="width:200px;" placeholder="请输入" />
                <span v-show="!isEdit" v-text="modelTemp.planField"></span>
              </FormItem>
            </Col>
             <Col span="12">
              <FormItem prop="startTime" label="计划开始时间">
                <DatePicker type="date" v-show="isEdit" placeholder="请选择" style="width:200px; " v-model="model.startTime"></DatePicker>
                <span v-show="!isEdit" v-text="$config.getDate(modelTemp.startTime)"></span>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem prop="endTime" label="计划结束时间">
                <DatePicker type="date" :options="opEndTime" v-show="isEdit" placeholder="请选择" style="width:200px;" v-model="model.endTime"></DatePicker>
                <span v-show="!isEdit" v-text="$config.getDate(modelTemp.endTime)"></span>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem prop="undertakingUnit" label="承办单位">
                <dict v-show="isEdit" model="model.undertakingUnit" :data="units" :value="model.undertakingUnit" code="CBDW" @click="getVal" style="width:200px;">
                </dict>
                <dict-span v-show="!isEdit" :data="units" :value="modelTemp.undertakingUnit" code="CBDW"></dict-span>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem prop="eventsType" label="比赛类型">
                <dict code="ZGX_BSLX" model="model.eventsType" :value="model.eventsType" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
                <dict-span v-show="!isEdit" code="ZGX_BSLX" :value="modelTemp.eventsType"></dict-span>
              </FormItem>
            </Col>
            <Col span="12" v-if="intersection(['1','2'],model.kindCodes) && isBatch">
            <FormItem prop="isWorldBatch" style="width:89%;" label="仅限世界积分排名成绩录入使用" :label-width="200">
              <i-switch v-model="model.isWorldBatch" :value="model.isWorldBatch" size="large" :true-value="'1'" :false-value="'0'">
                <span slot="open">是</span>
                <span slot="close">否</span>
              </i-switch>
            </FormItem>
            </Col>
            <Col span="12" v-if="intersection(['3','4','5','6','7','8'],model.kindCodes) && isBatch">
            <FormItem prop="isWorldBatch2" style="width:89%;" label="仅限积分排名成绩录入使用" :label-width="200">
              <i-switch v-model="model.isWorldBatch2" :value="model.isWorldBatch2" size="large" :true-value="'1'" :false-value="'0'">
                <span slot="open">是</span>
                <span slot="close">否</span>
              </i-switch>
            </FormItem>
            </Col>
            <Col span="12" v-if="intersection(['5','6','7','8'],model.kindCodes) && isBatch">
            <FormItem prop="youthEventsTypeBatch" style="width:89%;" label="赛事规格">
              <dict code="ZGX_QSNBSLX" model="model.youthEventsTypeBatch" :value="model.youthEventsTypeBatch" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
            </FormItem>
            </Col>
             <Col span="12" v-if="!isBatch">
            <FormItem prop="isWorld" style="width:89%;" :label="isWorldStr" :label-width="200">
              <i-switch v-show="isEdit" v-model="model.isWorld" :value="model.isWorld" size="large" :true-value="'1'" :false-value="'0'">
                <span slot="open">是</span>
                <span slot="close">否</span>
              </i-switch>
              <dict-span v-show="!isEdit" code='IS_FLAG' :value="modelTemp.isWorld"></dict-span>
            </FormItem>
            </Col>
            <Col span="12" v-if="['5','6','7','8'].includes(kindCode) && !isBatch">
            <FormItem prop="youthEventsType" style="width:89%;" label="赛事规格">
              <dict code="ZGX_QSNBSLX" model="model.youthEventsType" :value="model.youthEventsType" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
              <dict-span v-show="!isEdit" code='ZGX_QSNBSLX' :value="modelTemp.youthEventsType"></dict-span>
            </FormItem>
            </Col>
            <Col span="12" v-if="!isBatch&&model.eventsId&&['3','4','5','6','7','8'].includes(kindCode) && isEdit">
            <FormItem prop="kindCodeCopy" style="width:89%;" label="赛事类型复制">
              <Select placeholder="请选择" multiple v-model="kindCodeCopy" clearable style="width: 280px">
                <Option value="3" v-show="['3','4'].includes(kindCode)">男子业余</Option>
                <Option value="4" v-show="['3','4'].includes(kindCode)">女子业余</Option>
                <Option value="5" v-show="['5','6','7','8'].includes(kindCode)">青少年男子A组</Option>
                <Option value="6" v-show="['5','6','7','8'].includes(kindCode)">青少年女子A组</Option>
                <Option value="7" v-show="['5','6','7','8'].includes(kindCode)">青少年男子B组</Option>
                <Option value="8" v-show="['5','6','7','8'].includes(kindCode)">青少年女子B组</Option>
              </Select>
            </FormItem>
            </Col>
          </Row>
          </Col>
          <Col span="10">
          <Row>
            <Col span="12">
            <FormItem prop="logo" style="width:90%;" label="赛事LOGO">
              <upload-logo v-show="isEdit" :value="model.logo" @upload="upload"></upload-logo>
              <div v-show="!isEdit" class="demo-upload-list">
                <img style="height:146px; width:146px; position: relative;" :src="modelTemp.logo" />
                <div v-show="modelTemp.logo" class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(modelTemp.logo)"></Icon>
                </div>
              </div>
            </FormItem>
            </Col>
          </Row>
          </Col>
          <Col span="20">
          <Row>
            <Col>
            <FormItem prop="eventsIntroduce" style="width:89%;" label="赛事介绍">
              <editor v-show="isEdit" ref="editor" :value="model.eventsIntroduce" @on-change="handleChange" />
              <span v-show="!isEdit" v-html="$config.decodeHtml(modelTemp.eventsIntroduce)"></span>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col>
            <div class="right m-t-xl" style="width:89%;">
              <Button :to="'/game-management/'+$config.kindNameUrl(modelTemp.kindCode)+model.eventsId" v-show="!isEdit&&eventsId!=null&&!model.applyId">查看比赛安排</Button>
              <Button :to="'/game-apply-management/match/'+model.applyId" v-show="!isEdit&&eventsId!=null&&model.applyId">查看比赛安排</Button>
              <Button v-show="isEdit==true" @click="cancel">取消</Button>
              <Button v-show="isEdit==true" @click="save" class="m-l-md" type="primary">保存</Button>
              <Button v-show="isEdit==false" @click="edit" class="m-l-md" type="primary">编辑</Button>
            </div>
            </Col>
          </Row>
          </Col>
        </Form>
      </Row>
    </Card>

    <spin-temp v-if="loading"></spin-temp>
    <Modal title="图片预览" v-model="visible" class="modal-img-view">
      <img :src="imgUrl" style="width: 100%;">
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
  import dict from '_c/dict/dict.vue'
  import dictSpan from '_c/dict/dict-span.vue'
  import uploadLogo from '_c/upload/upload-logo.vue'
  import Editor from '_c/editor'
  import _ from 'lodash'
  import Api from '@/api/game'
  import ApiApply from '@/api/game-apply'
  import { getDict, check } from '@/api/configure'
  const api = new Api()
  const apiApply = new ApiApply()
  // 赛事管理
  export default {
    components: {
      dict,
      dictSpan,
      uploadLogo,
      Editor,
    },
    data() {
      return {
        initing: false,
        loading: false,
        isEdit: false,
        isBatch: false,
        access: this.$store.state.user.access,
        eventsId: this.$route.params.id,
        kindCode: this.$route.params.kindCode,
        type: this.$route.params.type,
        kindCodeCopy: [],
        units: [],
        visible: false,
        checkObj: {},
        imgUrl: null,
        opEndTime: {
          disabledDate: (date) => {
            let self = this
            return (
              date &&
              self.model.startTime &&
              self.model.startTime.valueOf() > date.valueOf()
            )
          },
        },
        isWorldStr: '仅限世界积分排名成绩录入使用',
        model: {
          eventsId: this.$route.params.id,
          kindCode: this.$route.params.kindCode,
          kindCodes: [],
          eventsType: '1',
          createBy: this.$store.state.userId,
          isWorld: '0',
          youthEventsType: null,
          isWorldBatch: '0',
          isWorldBatch2: '0',
          youthEventsTypeBatch: null,
          // eventsName: null,
          // competitionState: 1,
          // gradeCode: null,
          // startTime: null,
          // endTime: null,
          // planField: null,
          // undertakingUnit: null,
          // eventsIntroduce: null,
          // logo: null
        },
        modelTemp: {},
        ruleInline: {
          eventsName: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur',
            },
            {
              max: this.$config.INPUT_SIZE,
              message: `最多输入${this.$config.INPUT_SIZE}个字符`,
              trigger: 'blur',
            },
          ],
          eventsEnglishName: [
            {
              type: 'string',
              max: this.$config.INPUT_ENGLISH_SIZE,
              message: `最多输入${this.$config.INPUT_ENGLISH_SIZE}个字符`,
            },
          ],
          niandu: [{ required: true, message: '请选择' }],
          gradeCode: [{ required: true, message: '请选择' }],
          kindCode: [{ required: true, message: '请选择' }],
          kindCodes: [{ required: true, message: '请选择' }],
          // competitionState: [{ required: true, message: "请选择" }],
          planField: [
            { required: false, message: '请输入' },
            {
              pattern: this.$config.numReg,
              message: '请输入数字',
              trigger: 'blur',
            },
            {
              max: this.$config.INPUT_NUMBER_SIZE,
              message: `数字最长为${this.$config.INPUT_NUMBER_SIZE}位`,
              transform(value) {
                return value == null ? '' : value.toString()
              },
            },
          ],
          startTime: [
            {
              required: true,
              type: 'date',
              message: '请选择',
              trigger: 'change',
            },
          ],
          endTime: [
            {
              required: true,
              type: 'date',
              message: '请选择',
              trigger: 'change',
            },
          ],
          eventsType: [{ required: false, message: '请选择' }],
          undertakingUnit: [{ required: false, message: '请选择' }],
          logo: [{ required: false, message: '请选择赛事LOGO' }],
          isWorld: [{ required: true }],
          isWorldBatch: [{ required: true }],
          isWorldBatch2: [{ required: true }],
          youthEventsType: [{ required: true, message: '请选择' }],
          youthEventsTypeBatch: [{ required: true, message: '请选择' }],
          eventsIntroduce: [
            {
              required: false,
              type: 'string',
              message: '请输入',
              trigger: 'change',
            },
          ],
        },
      }
    },
    created() {
      if (this.$route.params.id != null) {
        check(this.$route.params.id).then((data) => {
          this.checkObj = data
          let str = null
          switch (data.verifyStatus) {
            case '0':
              str = '赛事公司正在处理这条赛事，请稍后处理'
              this.isEdit = null
              break
            case '1':
              str = '赛事公司已对这个赛事发起申请，请前往审核当前赛事'
              this.isEdit = null
              break
          }
          if (str != null) {
            if (this.access.includes('GAME_MANAGE')) {
              this.$Message.warning({
                content: str,
                // duration: 3,
                // closable: true
              })
            } else {
              this.$Message.warning({
                content: '该赛事已发起申请，请到申请赛事栏目处理',
                // duration: 3,
                // closable: true
              })
            }
          }
        })
      }

      if (this.$route.name === 'game-add-batch') {
        this.isBatch = true
        this.kindCode = '1'
      }
    },
    mounted() {
      let self = this
      getDict({ code: 'CBDW' })
        .then((data) => {
          self.units = data
          self.initing = true
          self.getGameById()
        })
        .catch((error) => {
          self.initing = true
          self.getGameById()
        })
    },
    watch: {
      'model.startTime': function (newVal) {
        let self = this
        if (newVal != null && newVal.valueOf() > self.model.endTime.valueOf()) {
          self.model.endTime = null
        }
      },
      // "model.kindCodes": function(newVal) {
      //   let self = this;
      //   if (newVal != null) {
      //     if (newVal.length == 0) {
      //       self.kindCode = null;
      //     } else if (newVal.length == 1) {
      //       self.kindCode = newVal[0];
      //     }
      //   }
      // }
    },
    methods: {
      intersection(arr, arr2) {
        return _.intersection(arr, arr2).length > 0
      },
      back() {
        let path = '/game-management/'
        let { kindCode } = this
        switch (kindCode) {
           case '-1':
            path += 'amateur'
            break
          case '0':
            path += 'teen'
            break
          case '1':
            path += 'career-man'
            break
          case '2':
            path += 'women/career-women'
            break
           case '20':
            path += 'women/women-two'
            break
          case '3':
            path += 'history/amateur/man'
            break
          case '4':
            path += 'history/amateur/women'
            break
          case '5':
            path += 'history/teen/man-a'
            break
          case '6':
            path += 'history/teen/women-a'
            break
          case '7':
            path += 'history/teen/man-b'
            break
          case '8':
            path += 'history/teen/women-b'
            break
          default:
            path += 'career-man'
            break
        }
        this.$router.push({ path })
      },
      handleView(url) {
        this.imgUrl = url
        this.visible = true
      },
      // 获取字典选择的值
      getVal(expression) {
        let self = this
        eval(expression)
      },
      // 获取文件上传地址
      upload(url) {
        this.model.logo = url
        this.$refs['model'].validateField('logo')
      },
      // 获取数据
      getGameById() {
        let self = this
        if (_.isEmpty(self.eventsId)) {
          self.isEdit = true
          if (!['1', '2'].includes(self.model.kindCode)) {
            self.isWorldStr = '仅限积分排名成绩录入使用'
          }
          return
        }
        self.loading = true
        api
          .getGameById(self.eventsId)
          .then((data) => {
            if (data.isWorld == null) {
              data.isWorld = '0'
            }
            if (!['1', '2'].includes(self.model.kindCode)) {
              self.isWorldStr = '仅限积分排名成绩录入使用'
            }
            self.modelTemp = data
            self.modelTemp.updateBy = self.$store.state.userId
            self.loading = false
          })
          .catch((error) => {
            self.loading = false
          })
      },
      // 分页
      changePage(pageNum) {
        this.page.current = pageNum
        this.fetchList()
      },
      save() {
        let self = this

        self.$refs['model'].validate((valid) => {
          if (valid) {
            self.loading = true
            self.model.niandu = self.$moment(self.model.niandu).format('YYYY')
            let primary = null
            if (!self.isBatch) {
              self.model = _.omit({ ...self.model }, [
                'kindCodes',
                'isWorldBatch',
                'isWorldBatch2',
                'youthEventsTypeBatch',
              ])
              if (self.access.includes('GAME_MANAGER')) {
                self.model.operationType = '2'
                primary = apiApply.edit(self.model)
              } else {
                primary = api.edit(self.model)
              }
              primary
                .then((data) => {
                  if (data) {
                    if (self.access.includes('GAME_MANAGER')) {
                      self.$router.push(`/game-apply-management/edit/${data}`)
                    } else {
                      if (self.kindCodeCopy.length > 0) {
                        let eventsId = self.model.eventsId || data
                        api
                          .copy({ eventsId, kindCodes: self.kindCodeCopy })
                          .then((cpres) => {
                            self.$router.go(-1)
                          })
                      } else {
                        self.$router.go(-1)
                      }
                    }
                  }
                  self.loading = false
                })
                .catch((error) => {
                  self.loading = false
                })
            } else {
              let models = []
              self.model.kindCodes.forEach((kindCode) => {
                let model = { ...self.model, kindCode }
                if (['1', '2'].includes(kindCode)) {
                  model.isWorld = model.isWorldBatch
                } else if (['3', '4', '5', '6', '7', '8'].includes(kindCode)) {
                  model.isWorld = model.isWorldBatch2
                  if (['5', '6', '7', '8'].includes(kindCode)) {
                    model.youthEventsType = model.youthEventsTypeBatch
                  }
                }
                model = _.omit({ ...model }, [
                  'kindCodes',
                  'isWorldBatch',
                  'isWorldBatch2',
                  'youthEventsTypeBatch',
                ])
                models.push(api.edit(model))
              })
              Promise.all(models).then((data) => {
                self.loading = false
                location.href = `/game-management/add/batch?t=${Math.random()}`
              })
            }
          }
        })
      },
      edit() {
        let self = this
        if (
          self.access.includes('GAME_MANAGER') &&
          self.checkObj.applyId != null &&
          self.checkObj.verifyStatus === '0'
        ) {
          self.$router.push(
            `/game-apply-management/edit/${self.checkObj.applyId}`
          )
        }
        self.model = _.omit(
          { ...self.modelTemp },
          'weiWriteCount',
          'yiWriteCount'
        )
        self.$refs.editor.setHtml(
          this.$config.decodeHtml(self.model.eventsIntroduce)
        )
        self.isEdit = true
        self.$forceUpdate()
      },
      cancel() {
        let self = this
        if (self.eventsId) {
          self.$refs['model'].resetFields()
          self.$refs.editor.setHtml('')
          self.model.isWorld = '0'
          self.model.youthEventsType = '1'
          self.model.gradeCode = '1'
          self.isEdit = false
          self.$forceUpdate()
          return
        }
        self.$router.go(-1)
      },
      handleChange(html, text) {
        if (text !== '' || /<iframe|<img/.test(html)) {
          this.model.eventsIntroduce = html
        } else {
          this.model.eventsIntroduce = ''
        }
        this.$refs['model'].validateField('eventsIntroduce')
      },
    },
  }
</script>
